<!-- pages/auth/index.vue -->
<template>
  <tm-app>
    <view class="auth-container">
      <!-- 标题 -->
      <tm-text label="欢迎使用音乐盒" :font-size="48" class="title" />

      <!-- 选项卡 -->
      <tm-tabs :list="tabs" :width="600" :height="80" item-direction="column" align="center" :round="2" class="tabs"
        :default-name="0" @change="tabsChange" transprent />

      <!-- 登录表单 -->
      <tm-sheet v-show="activeTab === 0" :margin="[24, 40]" :round="3">
        <tm-form :model="loginForm" label-position="top">
          <tm-input v-model="loginForm.phone" label="手机号" placeholder="请输入手机号" type="number" :max-length="11"
            clearable />

          <tm-input v-model="loginForm.password" label="密码" placeholder="请输入密码" password clearable :margin="[0, 30]" />

          <!-- <view class="form-extra">
            <tm-checkbox v-model="loginForm.remember">记住登录</tm-checkbox>
            <tm-text label="忘记密码？" color="primary" @click="navTo('forgot')" />
          </view> -->

          <tm-button label="立即登录" block :margin="[0, 40]" @click="handleLogin" />

          <!-- <tm-divider>
            <tm-text label="其他登录方式" color="grey" />
          </tm-divider>

          <view class="third-login">
            <tm-icon 
              name="tmicon-weixin" 
              color="#09bb07" 
              :font-size="80"
              @click="wechatLogin"
            />
          </view> -->
        </tm-form>
      </tm-sheet>

      <!-- 注册表单（简化版） -->
      <tm-sheet v-show="activeTab === 1" :margin="[24, 40]" :round="3">
        <tm-form :model="regForm" label-position="top">

          <tm-input v-model="regForm.username" label="用户名" placeholder="请输入用户名" :max-length="11" clearable
            class="mb-3" />
          <tm-input v-model="regForm.nickname" label="昵称" placeholder="请输入昵称" :max-length="11" clearable class="mb-3" />
          <tm-input v-model="regForm.phone" label="手机号" placeholder="请输入手机号" type="number" :max-length="11" clearable
            class="mb-3" />

          <tm-input v-model="regForm.password" label="密码" placeholder="8-20位字母数字组合" password clearable
            :margin="[0, 20]" />

          <tm-input v-model="regForm.rePassword" label="确认密码" placeholder="请再次输入密码" password clearable
            :margin="[0, 30]" />
            <tm-cell  :margin="[0,30]"  :padding="[0,0]" @click="showdate = true" title="请选择所在区域" :right-text="regForm.areaSelected[0] || '请选择'"></tm-cell>
            <tm-city-picker v-model:show="showdate" :selected-model="'name'" v-model="regForm.areaSelected" :modelStr="regForm.area" :city-level="'province'"></tm-city-picker>
          <tm-button label="立即注册" block color="green" @click="handleRegister" />
        </tm-form>
      </tm-sheet>
    </view>
  </tm-app>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {onLoad} from '@dcloudio/uni-app'
import { login, register } from '@/api/index'
// 选项卡配置
const activeTab = ref(0)
const tabs = ref([
  { key: 0, title: '账号登录' },
  { key: 1, title: '手机注册' }
])


const showdate = ref(false)

// 登录表单
const loginForm = reactive({
  phone: '',
  password: '',
})

// 注册表单（简化）
const regForm = reactive({
  username: '',
  nickname: '',
  phone: '',
  password: '',
  rePassword: '',
  area:'',
  areaSelected:[]
})

const tabsChange = (key) => {
  activeTab.value = key
}

onLoad(() => {
  console.log('onLoad');
  
  if(uni.getStorageSync('admin-token')){
    uni.switchTab({ url: '/pages/index/index' })
  }
})


// 登录提交
const handleLogin = () => {
  if (!validatePhone(loginForm.phone)) return
  if (loginForm.password.length < 6) {
    uni.showToast({ title: '密码至少6位', icon: 'none' })
    return
  }

  uni.showLoading({ title: '登录中...' })
  login(loginForm).then(({ data }) => {
    console.log(data)
    if (data.code === 200) {
      uni.setStorageSync('admin-token', data.data.token)
      uni.setStorageSync('userinfo', data.data)
      console.log(data.data.cateRelationVos);
      
      if (!data.data.cateRelationVos || data.data.cateRelationVos.length === 0) {
        setTimeout(() => {
          uni.hideLoading()
          uni.reLaunch({ url: '/pages/index/category' })
        }, 1000)
      } else {
        setTimeout(() => {
          uni.hideLoading()
          uni.switchTab({ url: '/pages/index/index' })
        }, 1000)
      }

    } else {
      uni.showToast({
        title: res.data.msg,
        icon: 'error',
        mask: true
      })
    }

  })


}

// 注册提交
const handleRegister = () => {
  console.log(regForm);
  regForm.area = regForm.areaSelected[0]
  
  if (!validateRegisterForm()) return

  register(regForm).then(res => {
    console.log(res)
  })

  uni.showLoading({ title: '注册中...' })
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({ title: '注册成功' })
    activeTab.value = 0
    resetRegForm()
    uni.reLaunch({ url: '/pages/index/login' })
  }, 1000)
}

// 表单验证
const validatePhone = (phone) => {
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    uni.showToast({ title: '手机号格式错误', icon: 'none' })
    return false
  }
  return true
}

const validateRegisterForm = () => {
  if (!validatePhone(regForm.phone)) return false
  if (regForm.password.length < 8) {
    uni.showToast({ title: '密码至少8位', icon: 'none' })
    return false
  }
  if (regForm.password !== regForm.rePassword) {
    uni.showToast({ title: '两次密码不一致', icon: 'none' })
    return false
  }
  return true
}

// 重置注册表单
const resetRegForm = () => {
  regForm.phone = ''
  regForm.password = ''
  regForm.rePassword = ''
}

// 其他方法保持不变...
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.auth-container {
  padding: 80rpx 40rpx;

  .title {
    text-align: center;
    margin-bottom: 80rpx;
  }

  .tabs {
    margin: 0 auto;
  }

  .form-extra {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 30rpx 0;
  }

  .third-login {
    display: flex;
    justify-content: center;
    padding: 40rpx 0;
  }
}
</style>
